package com.fourmob.datetimepicker.date;

import com.fourmob.datetimepicker.ResourceTable;

import ohos.agp.components.*;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class YearPickerView extends ListContainer implements ListContainer.ItemClickedListener,
	DatePickerDialog.OnDateChangedListener {
	private static HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x000110, "DatePickerDialogYear");
	private static TextViewWithCircularIndicator mTextViewWithCircular;
	private YearAdapter mAdapter;
	private int mChildSize;
	private DatePickerController mController;
	private TextViewWithCircularIndicator mSelectedView;
	private DirectionalLayout mSelectedLayout;
	private int mViewSize;

	public YearPickerView(Context context) {
		super(context);
	}

	/**
	 * 年份构造器
	 * @param context
	 * @param datePickerController
	 **/
	public YearPickerView(Context context, DatePickerController datePickerController) {
		super(context);
		HiLog.info(label, "YPV_YearPickerView");
		mController = datePickerController;
		mController.registerOnDateChangedListener(this);
		setLayoutConfig(new LayoutConfig(LayoutConfig.MATCH_PARENT,LayoutConfig.MATCH_CONTENT));
		HiLog.info(label, "YPV_YearPickerView01");
		setVerticalPadding(0,0);
	    mViewSize = 270;
	    mChildSize = 64;
		init(context);
		setItemClickedListener(this);
		setSelected(true);

		setPadding(10,10,10,10);
		HiLog.info(label, "YPV_YearPickerView02");
	}

	private void init(Context context) {
		HiLog.info(label, "YPV_init");
		ArrayList<String> years = new ArrayList<String>();
		for (int year = mController.getMinYear(); year <= mController.getMaxYear(); year++) {
			years.add(String.format("%d", year));
		}
		HiLog.info(label, "YPV_init01");
		mAdapter = new YearAdapter(context, ResourceTable.Layout_year_label_text_view, years);
		setItemProvider(mAdapter);
		HiLog.info(label, "YPV_init02");
	}

	@Override
	public void onDateChanged() {
		HiLog.info(label, "YPV_onDateChanged " + (mController.getSelectedDay().year
			- mController.getMinYear()));
		mAdapter.notifyDataChanged();
		postSetSelectionCentered(mController.getSelectedDay().year - mController.getMinYear());
		HiLog.info(label, "YPV_onDateChanged01");
	}

	private static int getYearFromTextView(Text view) {
		HiLog.info(label, "YPV_getYearFromTextView " + view.getText().toString());
		return Integer.valueOf(view.getText().toString());
	}

	@Override
	public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
		TextViewWithCircularIndicator clickedView1 = null;
		if (component == null) return;
		  DirectionalLayout clickedView = (DirectionalLayout) component;
		  clickedView1 = (TextViewWithCircularIndicator) clickedView.getComponentAt(0);

			if (clickedView != mSelectedLayout) {
				if (mSelectedView != null) {
					mSelectedView.drawIndicator(false);
					mSelectedView.postLayout();
				}
				clickedView1.drawIndicator(true);
				clickedView1.postLayout();
				mSelectedView = clickedView1;
			}
			HiLog.info(label, "YPV_onItemClicked02");
			mController.onYearSelected(getYearFromTextView(clickedView1));
			mAdapter.notifyDataChanged();
			HiLog.info(label, "YPV_onItemClicked03");

	}

	public void postSetSelectionCentered(int position) {
		HiLog.info(label, "YPV_postSetSelectionCentered01");
		postSetSelectionFromTop(position, mViewSize / 2 - mChildSize / 2);
		HiLog.info(label, "YPV_postSetSelectionCentered02");
	}

	public void postSetSelectionFromTop(final int position, final int y) {
		HiLog.info(label, "YPV_postSetSelectionFromTop " + position);
		mContext.getUITaskDispatcher().asyncDispatch(new Runnable() {
			@Override
			public void run() {
				HiLog.info(label, "YPV_postSetSelectionFromTop02 " + y);
				mTextViewWithCircular.getContentDescription();
			    scrollToCenter(position);

                moveChildToFront(mTextViewWithCircular);
			    postLayout();
				HiLog.info(label, "YPV_postSetSelectionFromTop"
					+ "03 " + mTextViewWithCircular.getContentDescription());
			}
		});
		HiLog.info(label, "YPV_postSetSelectionFromTop01");
	}

	private class YearAdapter extends BaseItemProvider {
		LayoutScatter layoutScatter;
		private List<String> mYears;
		private int resourceId;

		public YearAdapter(Context context, int resource, List<String> years) {
			super();
			HiLog.info(label, "YPV_YearAdapter");
			mYears = years;
			resourceId = resource;
			this.layoutScatter = LayoutScatter.getInstance(context);
		}

		@Override
		public int getCount() {
			HiLog.info(label, "YPV_getCount");
			return mYears.size();
		}

		@Override
		public Object getItem(int position) {
			HiLog.info(label, "YPV_getItem");
			return mYears.get(position);
		}

		@Override
		public long getItemId(int position) {
			HiLog.info(label, "YPV_getItemId");
			return position;
		}

		@Override
		public Component getComponent(int position, Component component,
									  ComponentContainer componentContainer) {
			HiLog.info(label, "YPV_getComponent");
			try {
				TextViewWithCircularIndicator v = new TextViewWithCircularIndicator(mContext,null);
				if (position == 0) {
					mTextViewWithCircular = v;
				}
			} catch (NotExistException e) {
				e.printStackTrace();
			} catch (WrongTypeException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			ViewHolder viewHolder = null;
			// component相当于view，其他的和ListView的适配器adapter差不多。
			// 名字区别也不大，不过ListView基本被淘汰了。
			if (component == null) {
				component = layoutScatter.parse(resourceId, null, true);
				viewHolder = new ViewHolder(component);
				component.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) component.getTag();
			}
            viewHolder.tvItemName.postLayout();
			int year = Integer.parseInt(mYears.get(position));
			boolean selected = mController.getSelectedDay().year == year;
			viewHolder.tvItemName.drawIndicator(selected);
			if (selected) {
				mSelectedView = viewHolder.tvItemName;
			}
			viewHolder.tvItemName.setText(year+"");
			return component;
		}
	}

	/**
	 * 列表缓存。
	 * 将已经显示在屏幕上的item缓存在ViewHolder中，下次再次出现直接从缓存中读取
	 */
	static class ViewHolder {
		TextViewWithCircularIndicator tvItemName;

		public ViewHolder(Component componentContainer) {
			tvItemName = (TextViewWithCircularIndicator) componentContainer.findComponentById(ResourceTable.Id_month_text_view);
			}
	}
}